package cn.qpyl.longpoll.netty;

import java.net.InetSocketAddress;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HttpServer {

    App app;

    public HttpServer(App a) {
        app = a;
    }

    public boolean start(int port) {
        // Configure the server.
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.option(ChannelOption.SO_BACKLOG, 4096);
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpServerInitializer(app));
            InetSocketAddress lAddr = new InetSocketAddress("0.0.0.0", port);
            Channel ch = b.bind(lAddr).sync().channel();

            log.error("Http Benchmark Service runing at {} ", lAddr.toString());

            ch.closeFuture().sync();
        } catch (Exception e) {
            log.error("Http Service Catch error : ", e.getCause());
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
        return true;
    }
}